<template>
  <div class="flowable-expression">
    <!-- 通用功能区 -->
    <el-card shadow="never" class="controls-card">
      <el-form 
        :model="queryParams" 
        ref="queryFormRef" 
        :inline="true" 
        v-show="showSearch" 
        label-width="68px" 
        class="demo-form-inline"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入表达式名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select 
            v-model="queryParams.status" 
            placeholder="请选择状态" 
            clearable
          >
            <template v-if="dict && dict.sys_common_status && Array.isArray(dict.sys_common_status.value)">
              <el-option
                v-for="(dictItem, index) in dict.sys_common_status.value"
                :key="dictItem && dictItem.value !== undefined ? dictItem.value : index"
                :label="dictItem && dictItem.label !== undefined ? dictItem.label : ''"
                :value="dictItem && dictItem.value !== undefined ? dictItem.value : undefined"
              />
            </template>
            <el-option v-else value="" label="加载中..." disabled />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            :icon="Search" 
            @click="handleQuery"
          >搜索</el-button>
          <el-button 
            :icon="Refresh" 
            @click="resetQuery"
          >重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            :icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:expression:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            :icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:expression:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            :icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:expression:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            :icon="Download"
            @click="handleExport"
            v-hasPermi="['system:expression:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>

    <!-- 主内容区 -->
    <el-card shadow="never" class="main-content-card">
      <el-table 
        v-loading="loading" 
        :data="expressionList" 
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" />
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="表达式内容" align="center" prop="expression" />
        <el-table-column label="指定类型" align="center" prop="dataType">
          <template #default="scope">
            <dict-tag 
              v-if="dict && dict.exp_data_type && Array.isArray(dict.exp_data_type.value)" 
              :options="dict.exp_data_type.value" 
              :value="scope.row.dataType"
            />
          </template>
        </el-table-column>
        <el-table-column 
          label="操作" 
          align="center" 
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              :icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:expression:edit']"
            >修改</el-button>
            <el-button
              link
              :icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:expression:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改流程达式对话框 -->
    <el-dialog 
      :title="title" 
      v-model="open" 
      width="500px" 
      append-to-body
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="请输入表达式名称" 
          />
        </el-form-item>
        <el-form-item label="内容" prop="expression">
          <el-input 
            v-model="form.expression" 
            placeholder="请输入表达式内容" 
          />
        </el-form-item>
        <el-form-item label="指定类型" prop="dataType">
          <el-radio-group 
            v-if="dict && dict.exp_data_type && Array.isArray(dict.exp_data_type.value)" 
            v-model="form.dataType"
          >
            <el-radio
              v-for="(dictItem, index) in dict.exp_data_type.value"
              :key="dictItem && dictItem.value !== undefined ? dictItem.value : index"
              :value="dictItem && dictItem.value !== undefined ? dictItem.value : undefined"
            >{{dictItem && dictItem.label !== undefined ? dictItem.label : ''}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group 
            v-if="dict && dict.sys_common_status && Array.isArray(dict.sys_common_status.value)" 
            v-model="form.status"
          >
            <el-radio
              v-for="(dictItem, index) in dict.sys_common_status.value"
              :key="dictItem && dictItem.value !== undefined ? dictItem.value : index"
              :value="dictItem && dictItem.value !== undefined ? parseInt(dictItem.value) : undefined"
            >{{dictItem && dictItem.label !== undefined ? dictItem.label : ''}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="form.remark" 
            placeholder="请输入备注" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="primary" 
            :loading="buttonLoading"
            @click="submitForm"
          >确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { 
  listExpression, 
  getExpression, 
  delExpression, 
  addExpression, 
  updateExpression 
} from "@/api/flowable/expression";
import { 
  Search, 
  Refresh, 
  Plus, 
  Edit, 
  Delete, 
  Download 
} from '@element-plus/icons-vue';
import { 
  getCurrentInstance, 
  ref, 
  reactive, 
  onMounted 
} from 'vue';
import { 
  ElMessage, 
  ElMessageBox 
} from 'element-plus';

const { proxy } = getCurrentInstance();
const dict = proxy.useDict('sys_common_status', 'exp_data_type');

// 遮罩层
const loading = ref(true);
// 按钮加载状态
const buttonLoading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 流程达式表格数据
const expressionList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  expression: null,
  status: null,
});
// 表单参数
const form = ref({
  dataType: 'fixed'
}); // 使用 ref 初始化为空对象，之后会被 reset 或接口数据填充
// 表单校验
const rules = reactive({
  // name: [
  //   { required: true, message: '请输入表达式名称', trigger: 'blur' },
  //   { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  // ],
  // expression: [
  //   { required: true, message: '请输入表达式内容', trigger: 'blur' }
  // ],
  // dataType: [
  //   { required: true, message: '请选择指定类型', trigger: 'change' }
  // ],
  // status: [
  //   { required: true, message: '请选择状态', trigger: 'change' }
  // ]
});

// 获取 queryForm Dom 元素
const queryFormRef = ref(null);
// 获取 form Dom 元素
const formRef = ref(null);

/** 查询流程达式列表 */
const getList = () => {
  loading.value = true;
  listExpression(queryParams).then(response => {
    expressionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    name: null,
    expression: null,
    dataType: null, // 修正：移除默认值设置
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加流程表达式";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value[0];
  getExpression(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改流程表达式";
  });
}

/** 提交按钮 */
function submitForm() {
  if (!formRef.value) return;
  
  formRef.value.validate(valid => {
    if (valid) {
      buttonLoading.value = true; // 开始加载状态
      
      if (form.value.id != null) {
        updateExpression(form.value).then(response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false; // 结束加载状态
        });
      } else {
        addExpression(form.value).then(response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false; // 结束加载状态
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const expressionIds = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除流程达式编号为"' + expressionIds + '"的数据项?', "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(function() {
      return delExpression(expressionIds);
    })
    .then(() => {
      getList();
      ElMessage.success("删除成功");
    });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/expression/export', {
    ...queryParams
  }, `表达式_${new Date().getTime()}.xlsx`);
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
/* .flowable-expression {} */

.controls-card {
  margin-bottom: 15px;
}

.main-content-card {
  height: 70vh; /* 设置容器固定高度 */
  display: flex;
  flex-direction: column;
}

:deep(.main-content-card .el-card__body) {
  flex-grow: 1; /* 使卡片主体填充可用空间 */
  overflow-y: auto; /* 当内容溢出时，在卡片主体上显示垂直滚动条 */
}

.mb8 {
  margin-bottom: 8px;
}

.demo-form-inline {
  display: flex;
  flex-flow: row wrap;
  align-items: center;
}

:deep(.demo-form-inline .el-input) {
  --el-input-width: 240px;
}

:deep(.demo-form-inline .el-select) {
  --el-select-width: 240px;
}

@media (max-width: 768px) {
  :deep(.demo-form-inline .el-form-item) {
    margin-right: 0;
    width: 100%;
  }
}
</style>